package com.example.aicompositiongrader.network;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitClient {
    // DeepSeek API基础URL
    private static final String BASE_URL = "https://api.deepseek.com/";
    private static Retrofit retrofit = null;
    // 请替换为你的DeepSeek API密钥
    private static final String API_KEY = "sk-d5fa25a1df2a44548741be6b0f58569e";

    // 超时时间设置
    private static final long CONNECT_TIMEOUT = 30; // 连接超时30秒
    private static final long READ_TIMEOUT = 60;    // 读取超时60秒
    private static final long WRITE_TIMEOUT = 30;   // 写入超时30秒
    private static final int MAX_RETRY_COUNT = 2;   // 最大重试次数

    public static ApiService getApiService() {
        if (retrofit == null) {
            // 添加日志拦截器
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);

            // 添加API密钥认证拦截器
            Interceptor authInterceptor = chain -> {
                Request original = chain.request();
                Request request = original.newBuilder()
                        .header("Authorization", "Bearer " + API_KEY)
                        .header("Content-Type", "application/json")
                        .method(original.method(), original.body())
                        .build();
                return chain.proceed(request);
            };

            // 添加重试拦截器
            Interceptor retryInterceptor = new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request request = chain.request();
                    Response response = null;
                    IOException lastException = null;

                    // 尝试最多MAX_RETRY_COUNT + 1次（初始1次 + 重试MAX_RETRY_COUNT次）
                    for (int i = 0; i <= MAX_RETRY_COUNT; i++) {
                        try {
                            response = chain.proceed(request);
                            // 如果响应成功或不是可重试的错误，直接返回
                            if (response.isSuccessful() || !isRetryable(response.code())) {
                                return response;
                            }
                            // 如果是可重试的错误，关闭当前响应并继续重试
                            response.close();
                        } catch (IOException e) {
                            lastException = e;
                            // 只有超时异常才重试
                            if (!(e instanceof java.net.SocketTimeoutException)) {
                                break;
                            }
                        }
                    }

                    // 所有尝试都失败，抛出最后一次异常
                    throw lastException != null ? lastException : new IOException("Unknown error");
                }

                // 判断是否是可重试的状态码
                private boolean isRetryable(int statusCode) {
                    return statusCode == 408    // 请求超时
                            || statusCode == 500 // 服务器内部错误
                            || statusCode == 502 // 网关错误
                            || statusCode == 503 // 服务不可用
                            || statusCode == 504; // 网关超时
                }
            };

            OkHttpClient client = new OkHttpClient.Builder()
                    .addInterceptor(logging)
                    .addInterceptor(authInterceptor)
                    .addInterceptor(retryInterceptor)
                    // 设置超时时间
                    .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                    .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                    .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
                    .build();

            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                    .build();
        }
        return retrofit.create(ApiService.class);
    }
}
